package com.face.server.controller;

import com.face.RespMsg;
import com.face.server.entity.Admin;
import com.face.server.repository.AdminRepository;
import com.face.server.service.CSVService;
import com.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import static java.util.stream.Collectors.toList;

@RestController
@RequestMapping("admin")
public class SuperAdminController {

    @Autowired
    AdminRepository adminRepository;

    @Autowired
    CSVService csvService;

    @GetMapping
    RespMsg all() {
        return RespMsg.build(adminRepository.findBySuper(false));
    }

    @PutMapping
    RespMsg batchSave(MultipartFile file) throws IOException {
        return file == null ?
                RespMsg.error("对不起，文件不能为空") :
                csvService.parseAdmin(file);
    }

    @PostMapping
    RespMsg save(@RequestBody @Validated Admin admin) {
        admin.getAuth().setUsername(admin.getPhone());
        admin.getAuth().setPassword(StringUtils.substringLast(admin.getIdentity(), 6));
        return RespMsg.build(adminRepository.save(admin).getId());
    }

    @DeleteMapping
    RespMsg delete(String[] admins) {
        if (admins == null)
            return RespMsg.error("对不起，请选择管理员");
        List<Admin> adminList = Arrays.stream(admins).map(s -> {
            Admin a = new Admin();
            a.setId(s);
            return a;
        }).collect(toList());
        adminRepository.delete(adminList);
        return RespMsg.build("删除成功");
    }

    @GetMapping("name/{name}")
    RespMsg findByName(@PathVariable String name) {
        return RespMsg.build(adminRepository.findByNameRegexAndNotSuper(name));
    }


    @Autowired
    UserController userController;

    @PostMapping("id/{id}")
    RespMsg addFile(MultipartFile file,@PathVariable String id) throws IOException {
        return userController.faceModels(file, id);
    }
}

